#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

srcdir=Open3D-${pkgver}

mkdir -p build

if [ -n "${feature_standalone_compile_tools}" ]; then
    mkdir -p build/bin || exit 1
    for tool in ShaderEncoder ShaderLinker; do
        ${CXX} -o build/bin/${tool} ${srcdir}/cmake/${tool}.cpp || exit 1
    done
    exit 0
fi

extra_args=()
if [ "${arch}" != "${host_arch}" ]; then
    extra_args+=(-DCMAKE_SYSTEM_NAME=Linux) # cross-compiling
    extra_args+=(-DCMAKE_SYSTEM_PROCESSOR=${arch})
    extra_args+=(-DFILAMENT_LIBRARY_DIRS=/usr/lib/${arch})
    extra_args+=(-DFILAMENT_MATC=/host/usr/bin/matc)
    if [ "${triple_env}" == "ohos" ]; then
        extra_args+=(-DOHOS=ON)
    fi
else
    extra_args+=(-DFILAMENT_LIBRARY_DIRS=/usr/lib)
    extra_args+=(-DFILAMENT_MATC=/usr/bin/matc)
fi

if [ -z "${feature_ipp}" ]; then
    extra_args+=(-DWITH_IPP=OFF)
fi

mv Open3D-PoissonRecon-90f3f064e275b275cff445881ecee5a7c495c9e0 PoissonRecon

cmake \
    -S ${srcdir} \
    -B build \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=/usr \
    -DCMAKE_INSTALL_LIBDIR=/usr/lib \
    -DUSE_SYSTEM_JSONCPP=ON \
    -DUSE_SYSTEM_PNG=ON \
    -DUSE_SYSTEM_QHULLCPP=ON \
    -DUSE_SYSTEM_FILAMENT=ON \
    -DUSE_SYSTEM_UVATLAS=ON \
    -DUSE_SYSTEM_GLFW=ON \
    -DUSE_SYSTEM_VTK=ON \
    -DUSE_SYSTEM_BLAS=ON \
    -DUSE_SYSTEM_FMT=ON \
    -DPOISSONRECON_USE_LOCAL_SOURCE=ON \
    -DUSE_SYSTEM_ZEROMQ=ON \
    -DBUILD_EXAMPLES=OFF \
    -DCMAKE_CXX_FLAGS="${CMAKE_CXX_FLAGS} -I/usr/include/openblas -I/usr/include/minizip" \
    -DUSE_SYSTEM_EIGEN3=ON \
    -DUSE_SYSTEM_EMBREE=ON \
    -DUSE_SYSTEM_TBB=ON \
    -DUSE_SYSTEM_JPEG=ON \
    -DUSE_SYSTEM_ASSIMP=ON \
    -DUSE_SYSTEM_CURL=ON \
    -DUSE_SYSTEM_OPENSSL=ON \
    -DFILAMENT_INCLUDE_DIRS=/usr/include \
    -DFILAMENT_LIBRARIES="filameshio;filament;filamat_lite;filamat;filaflat;filabridge;geometry;backend;bluegl;ibl;image;meshoptimizer;smol-v;utils;bluevk;vkshaders" \
    ${extra_args[@]} \
    || exit 1
make -C build -j ${MAX_JOBS} || exit 1
